<?php
/*
 * @Author: KingMin 
 * @Date: 2022-3-12 11:38:01 
 * @Last Modified by:   KingMin 
 * @Last Modified time: 2022-3-12 11:38:08
 * @The authors website: https://www.kingmin.cn  
 */
    require_once '../../init.php'; //引入主要程序
    
    // 引入七牛云上传必要程序
    
    use Qiniu\Auth;// 引入鉴权类
    use Qiniu\Storage\UploadManager;// 引入上传类
    
    // 引入阿里云上传必要程序
    use OSS\OssClient;
    use OSS\Core\OssException;
    
    
    if(!@$_FILES['file']){
        $url=KINGMIN_URL."/404";
        header("Location:$url");exit;
    }
    if(!is_uploaded_file(@$_FILES['file']['tmp_name'])) { 
        ajaxReturn (302,'上传的出错,上传类型不是通过POST上传',$_FILES['file']); 
    }
    // 获取参数
    $files=$_FILES['file'];//获取上传的参数
    $fileSize=$_FILES['file']['size'];//获取上传的参数的大小
    $fileSize=round($fileSize/1024,2);//转换为KB
    $fps=false;//分片上传吗
    if($fileSize>(6*1024)){ //文件大于6m启用分片上传
        $fps=true;
    }
    @$file_name=$_FILES['file']['name'];//上传文件的名字 
    // return $_FILES['file']
    // ajaxReturn (300,'调试',$_FILES['file']); 
    $hzname=substr($file_name,strrpos($file_name,"."));//文件的后缀名
    $hzname=substr($hzname,1);//去除后缀名前的点
    $hzname=strtolower($hzname);//通用转换为小写
    @$fid=$_POST['fid'];//文件夹id
    @$wapp=$_POST['wapp'];//是否为用户端
    @$uid=$_POST['uid'];//上传的用户uid
    @$type=$_POST['type'];//上传的文件类型
    $formType=getRequestFormType(false);
    if(!$formType){
        @$formType=$_POST['formType']??"wapp";
    }
    $loginuser=getLoginUser(true);
    if(@$loginuser['uid']){
        $uid=$loginuser['uid'];
    }
    
    $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
    // ajaxReturn (202,$formType,$loginuser); 
    // 上传设置参数
    
    $fileType='file';
    $att_type="";//允许上传的类型
    @$att_maxsize=intval(Option::get('att_maxsize'));//获取附件最大限制,单位M
    @$att_maxsize=$att_maxsize*1024; //转换为KB
    if($type){
        if($type=='1'){
            $fileType='image';
            $att_type=Option::get('img_type');
        }elseif($type=='2'){
            $fileType='video';
            $att_type=Option::get('video_type');
        }elseif($type=='3'){
            $fileType='audio';
            $att_type=Option::get('audio_type');
        }else{
            $att_type=Option::get('att_type');
        }
    }
    $att_type_list=[];
    if($att_type){
        $att_type_list=explode(',',$att_type);//转换为数组
    }
    @$storeType=intval(Option::get('storeType'));//从缓存中获取存储的类型  1为本地存储,2为七牛云存储,3为阿里云存储
    if(@!$storeType){
        $storeType=1;
    }
    
    $qiniuyun=[//获取七牛云的设置
        'accesskey'=>Option::get('qiniu_oss_secretKey'),
        'secretkey'=>Option::get('qiniu_oss_accessKey'),
        'bucket'=>Option::get('qiniu_oss_bucket'),
        'url'=>Option::get('qiniu_oss_url'),
    ];
    $aliyun=[//获取阿里云云的设置
        'accesskey'=>Option::get('aliy_oss_secretKey'),
        'secretkey'=>Option::get('aliy_oss_accessKey'),
        'bucket'=>Option::get('aliy_oss_bucket'),
        'endpoint'=>Option::get('aliy_oss_url'),
    ];
    
    // 判断上传标准
    
    // 是否超过了允许上传的限制
    if($fileSize>$att_maxsize){
        ajaxReturn (202,'上传的'.$fileType.'过大,只允许上传'.($att_maxsize>1024?($att_maxsize/1024).'M':$att_maxsize.'KB')); 
    }
    // 是否是允许的后缀名
    if(!in_array($hzname,$att_type_list)){
       if(!in_array('.'.$hzname,$att_type_list)){
            ajaxReturn (203,'只允许上传后缀名为：“'.$att_type.'”的'.$fileType."；当前后缀名为:".$hzname,$att_type_list); 
        }
    }
    
    
    if($storeType==2){
        if(!$qiniuyun['accesskey']){
            $storeType=1;
        }
    }
    if($storeType==3){
        if(!$aliyun['accesskey']){
            $storeType=1;
        }
    }
    // 上传文件返回格式
    
    $mydata = [
      'code' => 500,     //code码
      'msg' => "上传错误!!!",        //说明
      'fileSize' => $fileSize,       //文件大小
      'path' => "",          //文件绝对路径
      'url' => "",          //文件url
      'uptp' => "",          //输出地址
    ];
    
    //我们给每个用户动态的创建一个文件夹  
    $uptp="content/uploadfile/".$fileType."/admin/".($uid?$uid:'00000')."/".date("Y-m-d");
     // 随机生成图片的名字
    
    $tpUrl='/'.time().rand(1,1000).substr($file_name,strrpos($file_name,"."));
    if($wapp){
        // 前端用户的文件保存地址
        $uptp="/content/uploadfile/".$fileType."/webapp/".($uid?$uid:'00000')."/".$formType.'/'.date("Y-m-d");
    }
    if($storeType==1){
            //把文件转存到你希望的目录（不要使用copy函数）  
            $uploaded_file=$files['tmp_name'];  
            
            //文件绝对路径地址
            $user_path=$_SERVER['DOCUMENT_ROOT'].$uptp;
             
            //判断该用户文件夹是否已经有这个文件夹  
            if(!file_exists($user_path)) { 
                mkdir($user_path,0777,true);
            }  
         
           
        
            $move_to_file=$user_path.$tpUrl;//移动路径
            
            // 移动图片
            if(move_uploaded_file($uploaded_file,iconv("utf-8","gb2312",$move_to_file))) {
        		// echo  json_encode($dst_img);
        		$mydata['msg']=$fileType."上传成功";
        		$mydata['upfile']=$uploaded_file;
                $mydata['movepath']=$move_to_file;
        		$mydata['path']=$uptp.$tpUrl;
        		$mydata['code']=200;
        		$mydata['uptp']= $http_type.$_SERVER['SERVER_NAME'].$uptp.$tpUrl;
            } else {  
                $mydata['msg']="移动".$fileType."出错";
            }    
        
    }elseif($storeType==2){
        $uptp=$uptp.$tpUrl;
        $expires = 6000;
        $name=$files['name'];
        $etag=$files['tmp_name'];
        $fsize=$files['size'];
        $key=$files['type'];
        $policy = array(
        //   'callbackBody' => "key=$key&hash=$etag&bucket=$bucket&fsize=$fsize&name=$name",
          'callbackBody' => "key=$(key)&hash=$(etag)&bucket=$(bucket)&fsize=$(fsize)&name=$(x:name)",
          'callbackBodyType' => 'application/json'
        );
        //  ajaxReturn (300,"上传错误：",$policy); 
    	$auth = new Auth($qiniuyun['accesskey'], $qiniuyun['secretkey']);
        //生成token
        $token = $auth->uploadToken($qiniuyun['bucket'], null, $expires, $policy, true);
        // 初始化UploadManager类  
        $uploadMgr = new UploadManager();
         
        //  list($ret, $err) = $uploadMgr->putFile($token, $tp_name, $code['tmp_name']);
        $err="未执行七牛云上传";
        if($fps){
            // 如果指定了断点记录文件，那么下次会从指定的该文件尝试读取上次上传的进度，以实现断点续传
            $resumeFile = 'progress.log';
            // 分片上传可指定 version 字段，v2 表示使用分片上传 v2 , v1 表示 分片上传 v1 (默认 v1) , 选择 v2 可自定义分片大小，此处设为 6 MB，默认 4 MB
            $version = 'v1';
            $partSize = 6 * 1024 * 1024;
            list($ret, $err) = $uploadMgr->putFile(
                 $token, 
                 $uptp, 
                 $files['tmp_name'],
                  null,
                'application/octet-stream',
                 $resumeFile,
                 $version,
                 $partSize
            );
        }else{
             list($ret, $err) = $uploadMgr->putFile($token, $uptp, $files['tmp_name']);
        }
        if ($err !== null) {
            ajaxReturn (300,"上传错误：".$err,$err); 
        } else {
    	    $path=$qiniuyun['url'].$uptp;
    	    $mydata['msg']=$fileType."上传成功";
            $mydata['code']=200;
            $mydata['path']='/'.$uptp;
            $mydata['uptp']= $path;
        }
    }elseif ($storeType==3) {
            $expires = 6000;
            $name=$files['name'];
            $etag=$files['tmp_name'];
            $fsize=$files['size'];
            $key=$files['type'];
            // $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false);
            try{
                $ossClient = new OssClient($aliyun['accesskey'], $aliyun['secretkey'], $aliyun['endpoint']);
            
                // $ossClient->putObject($alybucket, $tp_name,  $etag);
            } catch(OssException $e) {
                printf(__FUNCTION__ . ": FAILED\n");
                printf($e->getMessage() . "\n");
                return;
            }
            try{
                // $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            
                $alybucket = $ossClient->createBucket($aliyun['bucket']);
                // $ossClient->putObject($alybucket, $tp_name,  $etag);
            } catch(OssException $e) {
                printf(__FUNCTION__ . ": FAILED\n");
                printf($e->getMessage() . "\n");
                return;
            }
            $imgOssUrl = $ossClient->uploadFile($aliyun['bucket'], $uptp,  $etag);

            ajaxReturn (300,"上传错误：",$imgOssUrl); 
    }else{
        ajaxReturn (400,"上传错误：没有存储的位置",); 
    }
        
    
    if($mydata['code']==200){
        $db = Database::getInstance();
        if(!$uid){$uid='0';}
        if($type=='1'){
            $imgdetail=getimagesize($mydata['uptp']);
            $remark=[
                    "width"=>$imgdetail[0],
                    "height"=>$imgdetail[1],
                    "format"=>$imgdetail['mime'],
                    "path"=>$mydata['path']
                ];
            $mydata['chat']=[
                "contentType"=>$files['type'],
                "name"=>$files['name'],
                "size"=>$files['size'],
                "url"=>$mydata['uptp'],
                "width"=>$imgdetail[0],
                "height"=>$imgdetail[1],
            ];
                // {"contentType":"image/jpg","name":"uni-image.jpg","size":126409,"url":"https://kmlove.oss-cn-chengdu.aliyuncs.com/goeasy-im-kmlove/uni-image_57206_202209231546.jpg","width":750,"height":300}
        }else{
            $remark=[
                "imgUrl"=>"",
                "width"=>"",
                "height"=>"",
                "dec"=>"",
                "path"=>$mydata['path']
            ];
        }
        if($type=='2'){
            //{"video":{"name":"uni-video_47461_202209231551.mp4","url":"https://kmlove.oss-cn-chengdu.aliyuncs.com/goeasy-im-kmlove/uni-video_47461_202209231551.mp4","width":720,"height":1280,"contentType":"video/mp4","size":315654,"duration":2},"thumbnail":{"name":"uni-thumbnail.jpg","url":"https://kmlove.oss-cn-chengdu.aliyuncs.com/goeasy-im-kmlove/uni-video_47461_202209231551.mp4?x-oss-process=video/snapshot,t_0000,f_jpg,w_720,m_fast,ar_auto","width":720,"height":1280,"contentType":"image/jpg"}}
            $thumbnail=$http_type.$_SERVER['SERVER_NAME']."/content/images/icon/videoPlay.jpg";
            if($storeType==2){
                $thumbnail="";
            }
            if($storeType==3){
                $thumbnail=$mydata['uptp']."?x-oss-process=video/snapshot,t_0000,f_jpg,w_720,m_fast,ar_auto";
            }
            
            $imgdetail=getimagesize($thumbnail);
            $mydata['chat']=[
                "video"=>[
                    "name"=>$files['name'],
                    "url"=>$mydata['uptp'],
                    "contentType"=>$files['type'],
                    "size"=>$files['size'],
                    "duration"=>0,
                ],
                "thumbnail"=>[
                    "name"=>"thumbnail",
                    "size"=>0,
                    "url"=>$thumbnail,
                    "contentType"=>$imgdetail['mime'],
                    "width"=>$imgdetail[0],
                    "height"=>$imgdetail[1],
                ],
            ];
        }
        if($wapp){
            $istype=1;
            $mydata['url']=$mydata['uptp'];
            echo json_encode($mydata,JSON_UNESCAPED_UNICODE);
            exit;
        }else{
            $istype=2;
        }
        $remark=json_encode($remark,JSON_UNESCAPED_UNICODE);
        $sql="insert into ".DB_PREFIX."sys_upload  ( `uid`, `fid`,`istype`,`isuptp`,`type`,`fname`,`fsize`,`url`,`ysurl`,`remark`) values('$uid',".
        " '$fid','$istype','$storeType','$type','$file_name','$fileSize','".$mydata['uptp']."','".$mydata['path']."','$remark')";
        $res=$db->query($sql);
        $imgid=$db->insert_id();
        if($res){
            if(!$wapp){
               $mydata['tp']=$fileType;
               $log_type="accessory";
               $log_title="上传".$fileType;
               $log_url='/admin/upload';
               $log_data['token']=$loginuser['token'];
               $log_data['data']=$mydata;
               $log_data=json_encode($log_data,JSON_UNESCAPED_UNICODE);
               @$msg= '【'.$loginuser['nickName'].'】,'.$log_title.'成功';
               @$caozuorz=addOperationLog($loginuser['uid'],"1","1",$log_type,$log_title,$log_url,$log_data,"","0",$msg);
            }
            $mydata['url']=$http_type.$_SERVER['SERVER_NAME']."/file/".$fileType."/".$imgid;
            echo json_encode($mydata,JSON_UNESCAPED_UNICODE);
            exit;
        }else{
           ajaxReturn (400,"上传".$fileType."出错"); 
        }
    }else{
        if(!$wapp){
            $log_type="accessory";
            $log_title="上传".$fileType;
            $log_url='/admin/upload';
            $log_data['token']=$loginuser['token'];
            $log_data['data']=$mydata;
            $log_data=json_encode($log_data,JSON_UNESCAPED_UNICODE);
            @$msg= '【'.$loginuser['nickName'].'】,'.$mydata['msg'];
            @$caozuorz=addOperationLog($loginuser['uid'],"1","1",$log_type,$log_title,$log_url,$log_data,"","0",$msg);
        }
        ajaxReturn ($mydata['code'],$mydata['msg'],$mydata); 
    }
    
     

?>